package com;
import java.sql.*;
public class DBManager {
	private Connection conn=null;
	private Statement stmt=null;
	private ResultSet rs=null;
	
	/**
	 * @return black SQL link object
	 */
	
//	link SQL
	public Connection ConnDB(){
		conn = null;
		try{
			String url ="jdbc:mysql://localhost:3306/alumniRecord";//PC MySql address,,?useUnicode=true&character=utf-8
			Class.forName("com.mysql.jdbc.Driver").newInstance();//loading JDBC
			conn = DriverManager.getConnection(url,"root","wangyang");//login MySql userName && password
			return conn;
		}
		catch(Exception fe){
			System.err.println("ConnDB():"+fe.getMessage());
			return null;
		}
		
	}
//	static{
//
//		try{
//			String url="jdbc:mysql://localhost:3306/test?useUnicode=true&character=utf-8";//PC MySql address
//			
//			Class.forName("com.mysql.jdbc.Driver");//��������;
//
//			conn=DriverManager.getConnection(url,"root","");//login MySql userName && password
//			return conn;
//		}catch(Exception fe){
//			throw new RuntimeException(fe,"���ݿ�����ʧ��");
//		}

//}

	/**
	 * @return back statusSet object
	 */
	
//	Statement CreatStat
	public Statement CreatStat(){
		stmt=null;
		try{
			if(conn==null){
				conn=this.ConnDB();
			}
			stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
			return stmt;
		}
		catch(Exception fe){
			System.err.println("CreatStat():"+fe.getMessage());
			return null;
		}
	}
	
	/**
	 * obtain preparedStatement method
	 * @param sql
	 * @param autoGenereateKeys
	 * @return
	 */
	public PreparedStatement preparStat(String sql,int autoGenereatedKeys){
		PreparedStatement pstmt=null;
		try{
			if(conn==null){
				conn=this.ConnDB();
			}
			pstmt=conn.prepareStatement(sql,autoGenereatedKeys);
		}
		catch(SQLException e){
			e.printStackTrace();
			return null;
		}
		return pstmt;
	}
	/**
	 * @param sql
	 * @return back pecordSet object
	 */
	public ResultSet getResult(String sql){
		rs=null;
		try{
		stmt=this.CreatStat();
		rs=stmt.executeQuery(sql);
		return rs;
	}
	catch (SQLException ex){
		System.err.println("getResult:"+ex.getMessage());
		return null;
		}
	}
	/**
	 * Method for executing update and delete statement
	 * @param sql
	 * @return
	 */
	public int executeSql(String sql){
		int RowCount;
		try{
			stmt=this.CreatStat();
			RowCount=stmt.executeUpdate(sql);
			if(!conn.getAutoCommit()){
			conn.commit();
		}
		return RowCount;
	}
	catch(Exception e){
		System.err.println("executesql:"+e.toString());
		return 0;
		}
	}
	/**
	 * Release resource method
	 */
	public void Release()throws SQLException{
		if(rs!=null){
			rs.close();
			rs=null;
		}
		if(stmt!=null){
			stmt.close();
			stmt=null;
		}
		if(conn!=null){
			conn.close();
			conn=null;
		}
	}
}

	
	
